package bot.controller;

import bot.conf.PathConf;
import bot.conf.TrustAllCertificates;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
public class HttpHelp {
    //GPT的token
    public static String GPTTOKEN ="Bearer " +"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkthY2giLCJpZCI6NDUzNzMsImVtYWlsIjoiMjU5NTkzMTc2N0BxcS5jb20iLCJyb2xlIjoidmlld2VyIiwib3BlbklkIjoibzlCTlM2YlFmN1VMdHQ3NzlBQWRDcU14NXVvbyIsImNsaWVudCI6bnVsbCwiaWF0IjoxNzE5ODM0NTc3LCJleHAiOjE3MjI0MjY1Nzd9.plwd2nXqnRhHd8PV2XlRx9qK3dpPhb2g3wR5";

    //获取图片数据
    public static String GetImageString(Integer status){
        String s ;
        s = sendGet("localhost:9000/send/getSend/"+status);//缓存服务器
        if(s == null || s.equals("")){
            s = sendGet("localhost:9000/image/getImage/"+status);//访问外部图片服务器
        }
        return s;
    }

    //访问
    public static String sendGet(String url) {
        String result = "";//返回的数据
        BufferedReader in = null;
        try {
            String urlNameString = "http://"+ url ;
            System.out.println(urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static String sendGetRequest(String urlString, Map<String, String> headers) throws IOException {
        // 创建URL对象
        URL url = new URL(urlString);
        // 打开连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 设置请求头
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        // 设置请求方式为GET
        conn.setRequestMethod("GET");

        // 从输入流获取响应内容
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer response = new StringBuffer();
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 关闭连接
        conn.disconnect();

        // 返回响应内容
        return response.toString();
    }
    /**
     * 向指定URL发送POST方法的请求
     *
     * @param url   请求URL
     * @param param 请求体字符串
     * @return 响应结果
     */
    public static String sendPost(String url, String param, Map<String, String> requestheader) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {

            // 创建SSL上下文
            SSLContext sslContext = SSLContext.getInstance("TLS");
            // 创建一个TrustManager数组，并使用上述实现类初始化
            TrustManager[] trustAllCerts = new TrustManager[]{new TrustAllCertificates()};
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // 设置默认的SSLSocketFactory和HostnameVerifier
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);


            URL realUrl = new URL("https://" + url);
            // 打开和URL之间的连接
            URLConnection conn = null;
            conn = realUrl.openConnection();
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(1000);
            if (requestheader != null) {
                // 自定义请求属性
                for (String key : requestheader.keySet())
                    conn.setRequestProperty(key, requestheader.get(key));
            } else {
                // 设置通用的请求属性
                conn.setRequestProperty("Content-Type","application/json");
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent",
                        "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
                //可设置header内的如token、密钥等功能，当然可以将此作为接口正式参数进行传递
                //conn.addRequestProperty("appkey","123465789");
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            //out = new PrintWriter(conn.getOutputStream());
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String sendPostRequest(String urlStr, Map<String, String> requestBody, Map<String, String> requestHeaders) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        // 创建SSL上下文
        SSLContext sslContext = SSLContext.getInstance("TLS");
        // 创建一个TrustManager数组，并使用上述实现类初始化
        TrustManager[] trustAllCerts = new TrustManager[]{new TrustAllCertificates()};
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // 设置默认的SSLSocketFactory和HostnameVerifier
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);

        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        StringBuilder requestBodyBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : requestBody.entrySet()) {
            requestBodyBuilder.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }
        requestBodyBuilder.deleteCharAt(requestBodyBuilder.length() - 1);
        String requestBodyString = requestBodyBuilder.toString();

        conn.getOutputStream().write(requestBodyString.getBytes());

        int responseCode = conn.getResponseCode();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        conn.disconnect();

        return response.toString();
    }


    private static byte[] getPostDataBytes(Map<String, String> params) throws Exception {
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (postData.length() != 0) {
                postData.append('&');
            }
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        return postData.toString().getBytes("UTF-8");
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String wlwHttpURLConnection(String url, String data) {

        StringBuffer sb = new StringBuffer();
        try {

            // 创建一个信任所有证书的SSL上下文
            TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                        public X509Certificate[] getAcceptedIssuers() { return null; }
                    }
            };

            // 设置SSL上下文，忽略证书验证
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

            URL realUrl = new URL(url);

            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);

            //请求方式为post
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);//自动处理重定向

            // 增加请求头 start
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.setRequestProperty("Authorization", GPTTOKEN);
            // 增加请求头 end
            connection.connect();

            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());// 创建输入输出流,用于往连接里面输出携带的参数
            String query = data.toString();

            dataout.write(query.getBytes("UTF-8"));
            dataout.flush();
            dataout.close();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "UTF-8");
                //gpt返回的对象是没有用逗号隔开的，要要手动添加，并且转为json数据时还要去掉最后一个逗号
                sb.append(lines + ",");
            }
            reader.close();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return sb.toString();
    }

    //调用第三方post请求,表单方式提交数据,百度识图专用
    public static String SendPostByFrom(MultipartFile file , String url , PathConf PathConf) throws IOException {
        CloseableHttpClient aDefault = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);//访问的地址
        // 构建 MultipartEntityBuilder
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //将MultipartFile转file

        File file1 = new File(PathConf.MtoFPath + System.currentTimeMillis() +".jpg");//图片暂存区
        //将file写入临时暂存区
        try(OutputStream outputStream = new FileOutputStream(file1)){
            outputStream.write(file.getBytes());
        }catch (Exception e){
            e.printStackTrace();
        }
        builder.addBinaryBody("image",file1);
        builder.addTextBody("tn","pc");
        builder.addTextBody("from","pc");
        builder.addTextBody("image_source","PC_UPLOAD_FILE");
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//        post.setHeader("Content-Type", "multipart/form-data; boundary=----");
        post.setHeader("Cookie","BIDUPSID=F0DD88B499D3DC02A76773EA2BBACAD9; PSTM=1677304194; __bid_n=186904e47732f447cb4207; BAIDUID=F1C76D8E0E9903CC7D0A88A80F0BBB11:FG=1; BAIDUID_BFESS=F1C76D8E0E9903CC7D0A88A80F0BBB11:FG=1; MAWEBCUID=web_EbCFGGjHdAxW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5MTg1OTBiOGJhZjg4NDZlMmFlOTBmZTJlMDkwYjliNTE1ZGY2NGE4MDE0YjJhY2NlNTJiMjk2ZDg2NGYwN2NkY2I3MDcwZWJhYTY5YTdjYzdiMmM3Y2M1YTM5M2I2MDA5ZWY5Zjk5MjU3Yjg3Y2Q1ZjIzMjlkYzM2ZmQ1NzdlNTMzYmY4Y2NiNGMyNWM2Ng==; antispam_data=8ea2da6ece773df2ae4c8a59a002e586912fca39ee16fb1a476995402e4ec6bc6a3dd5f124ca2d850af9180ce2bf7074dc45d1db3b810c206a9b21a5fc1181d1f05dbc77f0db357a8eb9961b4e1830c5; RT=\"z=1&dm=baidu.com&si=3dd5acfc-bff2-4b41-b3eb-d5ef6b10af23&ss=lptev7q8&sl=y&tt=oul&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&ld=xt86&ul=yo11&hd=yo17");
        HttpEntity build = builder.build();
        post.setEntity(build);
        //发送请求
        // 发送请求并获取响应
        HttpResponse response = aDefault.execute(post);
        //获取响应
        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line ;
        while ((line = bufferedReader.readLine()) != null){
            stringBuffer.append(line);
        }
        // 关闭连接
        aDefault.close();file1.delete();

        return stringBuffer.toString();
    }
}
